package comnet.rmi;

import java.rmi.ConnectException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Scanner;

/**
 * @author Mikko Puustinen (mikko.puustinen@gmail.com)
 * @version 0.1, 2008-jan-15
 */
public class RmiClient extends UnicastRemoteObject implements ClientActions {
    private ChatActions server;
    private static final long serialVersionUID = 3147352169106891654L;
    private String nickname;

    public RmiClient(ChatActions ca, String nickname) throws RemoteException {
        super();
        this.server = ca;
        this.nickname = nickname;
    }

    public void notifyNewMessage(String message) throws RemoteException {
        System.out.println(message);
    }

    public void runClient() throws RemoteException {
        Scanner scanner = new Scanner(System.in);
        try {
            while (true) {
                System.out.print("> ");
                String msg = scanner.nextLine();
                try {
                    server.newMessage(this, msg);
                } catch (ConnectException e) {
                    System.out.println("Error occured: " + e.getMessage());
                    return;
                } catch (RemoteException e) {
                    System.out.println("Error occured");
                }
            }
        } finally {
            server.newMessage(this, "/quit");
        }
    }

    public void endSession() throws RemoteException {
        System.exit(0);
    }

    public String getNickName() {
        return nickname;
    }

    public void setNickName(String nickname) throws RemoteException {
        this.nickname = nickname;
    }
}